from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters import rest_framework as filters
from .models import Category
from .serializers import CategorySerializer

class CategoryFilter(filters.FilterSet):
    name = filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Category
        fields = ['name', 'parent']

class CategoryViewSet(viewsets.ModelViewSet):
    """
    图书分类视图集
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_class = CategoryFilter
    search_fields = ['name', 'description']

    def get_queryset(self):
        """根据查询参数过滤分类"""
        queryset = Category.objects.all()

        # 获取顶级分类（没有父分类的分类）
        is_root = self.request.query_params.get('is_root', None)
        if is_root is not None:
            if is_root.lower() == 'true':
                queryset = queryset.filter(parent=None)
            else:
                queryset = queryset.exclude(parent=None)

        return queryset

    @action(detail=True, methods=['get'])
    def books(self, request, pk=None):
        """
        获取分类下的所有图书
        """
        category = self.get_object()
        books = category.get_all_books()

        # 导入BookSerializer，避免循环导入
        from books.serializers import BookSerializer
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['get'])
    def children(self, request, pk=None):
        """
        获取分类的所有子分类
        """
        category = self.get_object()
        children = category.get_children()
        serializer = self.get_serializer(children, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def tree(self, request):
        """
        获取分类树形结构
        """
        # 获取所有顶级分类
        root_categories = Category.objects.filter(parent=None)

        def build_tree(category):
            """递归构建分类树"""
            data = CategorySerializer(category).data
            children = Category.objects.filter(parent=category)
            if children:
                data['children'] = [build_tree(child) for child in children]
            return data

        tree_data = [build_tree(category) for category in root_categories]
        return Response(tree_data)
